importScripts("../src/webrpc.js");

new webrpc.Service("primeService", {
    n: 1,
    stopped: true,
    loop: function() {
	for (var i = 0; i < 1000000000; i++) {
	    ;
	}
	return 10000;
    },
    startCalculation: function(){
        webrpc.parent.outputService.output("ok: " + this.stopped);
        var self = this;
        self.stopped = false;
        function searchPrime(){
            if (self.stopped) {
                return;
            }
            var found = 0;
            search: while (true) {
                self.n += 1;
                for (var i = 2; i <= Math.sqrt(self.n); i += 1) {
                    if (self.n % i == 0) 
                        continue search;
                }
                // found a prime!
                webrpc.parent.outputService.output(self.n);
                found++;
                if (found == 10) {
                    setTimeout(searchPrime, 0);
                    return;
                }
            }
        }
        searchPrime();
    },
    pauseCalculation: function(){
        this.stopped = true;
    },
    stopCalculation: function(){
        this.pauseCalculation();
        this.n = 1;
    }
});
